<?php
/**
 * @package		OpenCart
 * @author		Daniel Kerr
 * @copyright	Copyright (c) 2005 - 2017, OpenCart, Ltd. (https://www.opencart.com/)
 * @license		https://opensource.org/licenses/GPL-3.0
 * @link		https://www.opencart.com
*/

/**
* Model class
* @property DB db
* @property Cache cache
* @property Request request
* @property \Cart\Cart cart
*/
abstract class Model {
    /**
     * @var Registry
     */
	protected $registry;

	public function __construct($registry) {
		$this->registry = $registry;
	}

	public function __get($key) {
		return $this->registry->get($key);
	}

	public function __set($key, $value) {
		$this->registry->set($key, $value);
	}

    public function getTable()
    {
        if (! isset($this->table)) {
            throw new \InvalidArgumentException('property [table] not set');
        }

        return DB_PREFIX . $this->table;
    }

    public function getKeyName()
    {
        if (! isset($this->table)) {
            throw new \InvalidArgumentException('property [table] not set');
        }

        return $this->table . '_id';
    }

    /**
     * @example - for SQL SET clause
     *   assembleSetSql([ 'a' => 1, 'b' => 2])
     *   => "`a` = '1', `b` = '2'"
     *
     * @param $col_vals
     *
     * @return string
     */
    protected function assembleSetSql($col_vals)
    {
        $sql = '';
        foreach ($col_vals as $column => $value)
        {
            $comma = $sql ? ',' : '';
            $sql .= "$comma`$column` = '$value'";
        }

        return $sql;
    }

    /**
     * @example - for SQL SET clause
     *   assembleValuesSql([
     *      ['a' => 1, 'b' => 2],
     *      ['a' => 3, 'b' => 4],
     *   ])
     *   => " (a,b) VALUES (1,2),(3,4) "
     *
     * @param $insert_vals
     *
     * @return string
     */
    protected function assembleValuesSql($insert_vals)
    {
        $keys_sql = '(' . implode(',', array_keys($insert_vals[0])) . ')';
        $values_sql = '';
        foreach ($insert_vals as $values)
        {
            $comma = $values_sql ? ',' : '';
            $values_sql .= $comma . "('" . implode("','", array_values($values)) . "')";
        }

        return " $keys_sql VALUES $values_sql ";
    }

    protected function cartFilter()
    {
        return [
            'check_cart_ids' => $this->session->data['check_cart_ids'] ?? []
        ];
    }
}